<?php

namespace Xin\EasyQueue;

use DateTimeInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use support\Container as WebmanContainer;
use Xin\EasyQueue\Contracts\Dispatcher;
use Xin\Support\Framework;

class PendingDispatch
{
    /**
     * @var array
     */
    protected $options = [
        'queue' => 'default',
        'connection' => 'default',
        'delay' => null,
        'data' => null,
    ];

    /**
     * @param string|null $queue
     * @param string|null $connection
     */
    public function __construct($data, string $queue = null, string $connection = null)
    {
        $this->options['data'] = $data;
        $queue && $this->options['queue'] = $queue;
        $connection && $this->options['connection'] = $connection;

        Initializer::run();
    }

    /**
     * 设置队列名称
     * @param string $queue
     * @return PendingDispatch
     */
    public function queue(string $queue): self
    {
        $this->options['queue'] = $queue;

        return $this;
    }

    /**
     * 设置链接
     * @param string $connection
     * @return $this
     */
    public function connection(string $connection): self
    {
        $this->options['connection'] = $connection;

        return $this;
    }

    /**
     * 设置延迟时间
     * @param mixed $delay
     * @return $this
     */
    public function delay($delay): self
    {
        if ($delay instanceof DateTimeInterface) {
            $delay = $delay->getTimestamp() - now()->getTimestamp();
        }

        $this->options['delay'] = $delay;

        return $this;
    }

    /**
     * @return bool
     */
    protected function shouldDispatch(): bool
    {
        return $this->options['queue'] && $this->options['connection'];
    }

    /**
     * Handle the object's destruction.
     *
     * @return void
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function __destruct()
    {
        if (!$this->shouldDispatch()) {
            return;
        }

        Framework::container()->get(Dispatcher::class)->dispatch($this->options);
    }


}
